package org.thanos.demo.file;

import com.mongodb.client.gridfs.model.GridFSFile;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;


@Service("fileService")
public class FileServiceImpl implements FileService {

    @Autowired
    private GridFsTemplate gridFsTemplate;

    /**
     * 存储文件到系统
     *
     * @param file 文件
     * @return 文件名
     */
    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // Normalize file name
        String type = Objects.requireNonNull(file.getOriginalFilename()).split("\\.")[1];
        String fileName = UUID.randomUUID().toString() + "_" + System.currentTimeMillis() + "." + type;
        ObjectId fileResult = gridFsTemplate.store(file.getInputStream(), fileName, file.getContentType());
        return fileResult.toHexString();
    }

    @Override
    public void downloadFile(String objectId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //根据文件id查询文件
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(objectId)));
        //使用GridFsBucket打开一个下载流对象
        GridFsResource gridFsResource = gridFsTemplate.getResource(Objects.requireNonNull(gridFSFile));
        String fileName = Objects.requireNonNull(gridFsResource.getGridFSFile()).getFilename();
        //处理中文文件名乱码
        if (request.getHeader(HttpHeaders.USER_AGENT).toUpperCase().contains("MSIE") ||
                request.getHeader(HttpHeaders.USER_AGENT).toUpperCase().contains("TRIDENT")
                || request.getHeader(HttpHeaders.USER_AGENT).toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8.displayName());
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        // 通知浏览器进行文件下载
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileName + "\"");
        IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());
    }
}
